package activitys;

import io.web.JSONConnector;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;
import misc.SpecialAdapter;
import nl.preflag.basewars.R;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;

/**
 * @author Patrick van Gils, 0787862, INF3M
 * Search activity
 */

public class SearchListActivity extends Activity {
	
	private String query, USER_ID;
	private JSONConnector webby;
	private JSONArray searchListJson;
	public HashMap<String, String> map, o, baseMap;
	private ImageButton searchMapButton, searchFriendButton;
	
	@Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.search_list);
        
        Bundle extras = getIntent().getExtras();        
        query = extras.getString("query");
        
        SharedPreferences pref = getSharedPreferences("programSettings", MODE_PRIVATE);
        USER_ID = pref.getString("userId", null);
        
        setView();
        fillSearchList();
    }
	
	/**
	 * Set the view
	 */
	private void setView() {
		searchMapButton = (ImageButton) findViewById(R.id.searchMapFriendButton);
		searchFriendButton = (ImageButton) findViewById(R.id.searchFriendListButton);
		
		searchMapButton.setOnClickListener(new View.OnClickListener() {
	          public void onClick(View v) {
	        	  openMapView();
	          }
		});
		
		searchFriendButton.setOnClickListener(new View.OnClickListener() {
	          public void onClick(View v) {
	        	  openFriendView();
	          }
		});
	}
	
	/**
     * Fill the listview with base info
     * 
     */
	private void fillSearchList() {
		
		final ListView lv = (ListView) findViewById(R.id.searchListListView);
		String[] from = new String[] {"email", "username"};
		int[] to = new int[] { R.id.searchListUsernameTextView, R.id.searchListEmailTextView};
		
		List<HashMap<String, String>> fillMaps = new ArrayList<HashMap<String, String>>();
    	try 
    	{
    		webby = new JSONConnector();
    		searchListJson = webby.connect("/User/!%60email%60%20LIKE%20'%25"+query+"%25'%20OR%20%60username%60%20LIKE%20'%25"+query+"%25'", "result", false);

    		for(int i=0;i<searchListJson.length();i++) 
    		{
    			map = new HashMap<String, String>();	
    			JSONObject e = searchListJson.getJSONObject(i);
    			
    			map.put("id",  ""+e.getInt("id"));
    			map.put("email", e.getString("email"));
    			map.put("username", e.getString("username"));
    			fillMaps.add(map);	
    		}
	     	
	   	} catch (Exception e) 
	   	{
	   		e.printStackTrace();
	   	}
    	
    	// fill in the grid_item layout
        SpecialAdapter adapter = new SpecialAdapter(this, fillMaps, R.layout.search_list_item, from, to);
        lv.setAdapter(adapter);
        lv.setOnItemClickListener(new OnItemClickListener() {
        	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        		@SuppressWarnings("unchecked")
        		HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);
        		try
        		{
                    final List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
                    nameValuePairs.add(new BasicNameValuePair("user_id", USER_ID));
                    nameValuePairs.add(new BasicNameValuePair("friend_id", o.get("id")));
                    webby = new JSONConnector();
            		webby.requestPostObject("/addfriend", nameValuePairs);
            		openFriendView();
        		} catch (Exception e) {
        			e.printStackTrace();
        		}

			}
		});
	}	
	
	
	/**
	 * Open the map activity
	 */
	private void openMapView() {
		finish();
	}
	
	/**
	 * Open the map activity
	 */
	private void openFriendView() {
		Intent mmIntent = new Intent(SearchListActivity.this, FriendListActivity.class);
		startActivityForResult(mmIntent, 0);
		finish();
	}
}
